<template>
  <div class="patient-management">
    <div class="header">
      <h2>患者管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>添加患者
      </el-button>
    </div>

    <div class="filter-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索患者姓名"
        clearable
        style="width: 300px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="filterOption" placeholder="按日期排列" clearable>
        <el-option label="按日期升序" value="asc"></el-option>
        <el-option label="按日期降序" value="desc"></el-option>
      </el-select>
    </div>

    <el-table :data="filteredPatients" style="width: 100%" v-loading="patientStore.loading">
      <el-table-column prop="name" label="姓名" width="200" />
      <el-table-column prop="gender" label="性别" width="300" />
      <el-table-column prop="age" label="年龄" width="200" />
      <el-table-column prop="phone" label="电话" width="300" />
      <el-table-column prop="visitDate" label="就诊日期" width="300" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button size="small" @click="viewPatient(scope.row)">查看</el-button>
          <el-button size="small" type="danger" @click="deletePatient(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加患者对话框 -->
    <el-dialog v-model="showAddDialog" title="添加新患者" width="50%">
      <patient-form @submit="handleAddPatient" @cancel="showAddDialog = false" />
    </el-dialog>

    <!-- 编辑患者对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑患者信息" width="50%">
      <patient-form 
        v-if="currentEditPatient"
        :initial-data="currentEditPatient" 
        @submit="handleEditPatient" 
        @cancel="showEditDialog = false" 
      />
    </el-dialog>

    <!-- 查看患者详细信息对话框 -->
    <el-dialog v-model="showViewDialog" title="患者信息" width="600px">
      <patient-detail
        v-if="currentPatient"
        :patient="currentPatient"
        @close="showViewDialog = false"
        @edit="handleEdit"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { usePatientStore } from '@/stores/patientStore'
import PatientForm from '@/components/PatientForm.vue'
import PatientDetail from '@/components/PatientDetail.vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const patientStore = usePatientStore()

const searchQuery = ref('')
const filterOption = ref('desc')
const showAddDialog = ref(false)
const showViewDialog = ref(false)
const showEditDialog = ref(false)
const currentPatient = ref(null)
const currentEditPatient = ref(null)

// 初始化加载数据
onMounted(() => {
  patientStore.fetchPatients()
})

// 过滤和排序患者列表
const filteredPatients = computed(() => {
  let result = [...patientStore.patients]

  // 按姓名搜索
  if (searchQuery.value) {
    result = result.filter(patient =>
      patient.name.includes(searchQuery.value)
    )
  }

  // 按日期排序
  if (filterOption.value === 'asc') {
    result.sort((a, b) => new Date(a.visitDate) - new Date(b.visitDate))
  } else if (filterOption.value === 'desc') {
    result.sort((a, b) => new Date(b.visitDate) - new Date(a.visitDate))
  }

  return result
})

// 查看患者详情
const viewPatient = async (patient) => {
  try {
    const detailedPatient = await patientStore.fetchPatientById(patient.id)
    currentPatient.value = detailedPatient
    showViewDialog.value = true
  } catch (error) {
    ElMessage.error('获取患者详情失败')
  }
}

// 删除患者
const deletePatient = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该患者吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await patientStore.deletePatient(id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 添加患者
const handleAddPatient = async (newPatient) => {
  try {
    await patientStore.addPatient(newPatient)
    showAddDialog.value = false
    ElMessage.success('患者添加成功')
  } catch (error) {
    ElMessage.error('添加患者失败')
  throw error
  }
}

// 处理编辑请求
const handleEdit = (patient) => {
  currentEditPatient.value = { ...patient }
  showEditDialog.value = true
}

// 提交编辑后的患者信息
const handleEditPatient = async (updatedPatient) => {
  try {
    await patientStore.updatePatient(updatedPatient.id, updatedPatient)
    showEditDialog.value = false
    ElMessage.success('患者信息更新成功')
  } catch (error) {
    ElMessage.error('更新患者信息失败')
    throw error
  }
}
</script>

<style scoped>
/* 保持您原有的样式不变 */
.patient-management {
  padding: 30px;
  background-color: #f0f4f8;
  min-height: 100vh;
  font-family: 'Segoe UI', sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.header h2 {
  color: #2c3e50;
  font-weight: 600;
}

.filter-bar {
  display: flex;
  gap: 20px;
  margin-bottom: 25px;
}

.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  background-color: #ffffff;
  transition: all 0.3s ease;
}

.el-table :deep(th) {
  background-color: #e9f1fa !important;
  color: #1a73e8;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.el-table :deep(tr:hover) {
  background-color: #f1f9ff !important;
}

.el-table-column {
  transition: all 0.3s ease;
}

/* 按钮美化 */
.el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease-in-out;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-button--primary {
  background-color: #1a73e8;
  border-color: #1a73e8;
}

.el-button--primary:hover {
  background-color: #155ea1;
  border-color: #155ea1;
}

.el-button--danger {
  background-color: #d93025;
  border-color: #d93025;
}

.el-button--danger:hover {
  background-color: #a6241d;
  border-color: #a6241d;
}

/* 输入框与下拉选择器美化 */
.el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  padding-left: 40px;
  transition: all 0.2s ease;
}

.el-input__inner:focus {
  border-color: #1a73e8;
  box-shadow: 0 0 8px rgba(26, 115, 232, 0.2);
}

.el-select .el-input__inner {
  padding-right: 40px;
}

/* 图标前缀美化 */
.el-input__prefix {
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #888;
}

/* 对话框动画 */
:deep(.el-dialog) {
  border-radius: 16px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
  transition: all 0.3s ease;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
}

:deep(.el-dialog__title) {
  font-size: 1.2rem;
  font-weight: 600;
  color: #2c3e50;
}
</style>